<template>
  <div class="g-inherit m-article" v-if="isOpen">
    <div class="top-header border-bottom fixed-top" style="z-index:100">
      <div class="top-back">
        <a @click="onClickBack">返回</a>
      </div>
      <h2 class="f36 color-000">5173客服</h2>
      <!--<h2 class="f36 color-000">{{sessionName}}</h2>-->
      <div class="top-right">
        <a @click="showOrder" class="imorder f32 color-36c" style="color: #3f6fcf !important;">订单信息</a>
        <!--<a @click="goHistory" class="imorder f32 color-36c">聊天记录</a>-->
      </div>
    </div>
    <OrderInfoComponent
      :scene="scene"
      :to="to"
      v-show="orderShow"></OrderInfoComponent>
    <div>
      <chat-list
        type="session"
        :msglist="msglists"
        :userInfos="userInfos"
        :robotInfos="robotInfos"
        :myInfo="myInfo"
        :isRobot="isRobot"
        @msgs-loaded="msgsLoaded"
      ></chat-list>
      <chat-editor
        type="session"
        :scene="scene"
        :to="to"
        :isRobot="isRobot"
      ></chat-editor>
    </div>
  </div>
</template>

<script>
import ChatEditor from './components/ChatEditor'
import ChatList from './components/ChatList'
import util from 'js/utils'
import pageUtil from 'js/utils/page'
import { mapState, mapGetters, mapActions } from 'vuex'
import OrderInfoComponent from './components/OrderInfoComponent'
import api from 'api/index';
//import config from 'components/im/config'
import SDK from 'components/im/sdk/NIM_Web_SDK_v4.0.0.js'

export default {
  components: {
    ChatEditor,
    ChatList,
    OrderInfoComponent
  },
beforeRouteEnter (to, from, next) {
    next(vm => {
      if(from.name=='home'){
        vm.$http.jsonp('//ordermessage.5173.com/api/message/Read',{
          'jsonp':'jsoncallback',
          params:{
            orderId:vm.$route.params.orderInfo
          }
        })
          .then((res)=>{
              console.log(res)
            },
            error=>{
              console.log(error)
            }
          )
      }
    })
  },
  created(){
    let loginInfo = {
      uid: this.$getCookie('uid'),
      sdktoken: this.$getCookie('sdktoken'),
    }
    this.$store.dispatch('initNimSDK', loginInfo)
  },
  beforeMount(){
    this.$store.dispatch('setSDK',SDK)
  },
  mounted () {
    //console.log(config)
    //不从云端获取历史记录,获取记录走接口
   /* this.$store.dispatch('getHistoryMsgs', {
      scene: this.scene,
      to: this.to
    })*/

    window.addEventListener('scroll', this.handleScroll)
   this.getImHistory().then(res=>{
       this.$nextTick(()=>{
       if (this.msglists && this.msglists.length<10) {
         this.getImHistory()
       }
     })
   })
    this.$store.dispatch('showLoading')
    // 此时设置当前会话
    this.$store.dispatch('setCurrSession', this.sessionId)
    pageUtil.scrollChatListDown()
    setTimeout(() => {
      this.$store.dispatch('hideLoading')
      let height=document.getElementById('chat-list').scrollHeight
      document.body.scrollTop=height
    }, 1000)
    if (this.orderId&&this.orderType) {
      this.getDefaultData()
    }
  },
  updated () {
    //不从云端获取历史记录,获取记录走接口
    /*if (!this.msglist.length) {
      this.$store.dispatch('getHistoryMsgs', {
        scene: this.scene,
        to: this.to
      })
    }
    pageUtil.scrollChatListDown()*/
  },
  // 离开该页面，此时重置当前会话
  destroyed () {
    this.ispushed=false;
    this.$store.dispatch('resetCurrSession')
    this.$store.dispatch('logout')
    this.$setCookie("appkey","",'/',"-1");
    this.$setCookie("uid","",'/',"-1");
    this.$setCookie("sdktoken","",'/',"-1");
  },
  data () {
    return {
      isfinish:false,
      height:0,
      afterHeight:0,
      ispushed:false,
      scroll:null,
      msglists:[],
      getMsgList:[],
      isOpen:true,
      leftBtnOptions: {
        backText: ' ',
        preventGoBack: true,
      },
      orderInfo: this.$route.params.orderInfo,
      orderShow: false,
      messageid:''
     //msglist:[]
    }
  },
  computed: {
    /*orderType() {
      if (/-/.test(this.orderInfo)) {
        return this.orderInfo.split('-')[0]
      }
    },*/
    orderId() {
     /* if (/-/.test(this.orderInfo)) {*/
        return this.orderInfo
     /* }*/
    },
    sessionId () {
      let sessionId
      if(this.$route.params.sessionId.indexOf('%')>-1){
        sessionId=this.$route.params.sessionId.replace('%','@5173.com')
      }else{
        sessionId= this.$route.params.sessionId
      }
      return sessionId
    },
    sessionName () {
      let sessionId = this.sessionId
      let user = null
      if (/^p2p-/.test(sessionId)) {
        user = sessionId.replace(/^p2p-/, '')
        if (user === this.$store.state.im.userUID) {
          return '我的手机'
        } else if (this.isRobot) {
          return this.robotInfos[user].nick
        } else {
          let userInfo = this.userInfos[user] || {}
          return util.getFriendAlias(userInfo)
        }
      } else if (/^team-/.test(sessionId)) {
        return '群'
      }
    },
    scene () {
      return util.parseSession(this.sessionId).scene
    },
    to () {
      return util.parseSession(this.sessionId).to
    },
    // 判断是否是机器人
    isRobot () {
      let sessionId = this.sessionId
      let user = null
      if (/^p2p-/.test(sessionId)) {
        user = sessionId.replace(/^p2p-/, '')
        if (this.robotInfos[user]) {
          return true
        }
      }
      return false
    },
    myInfo () {
      return this.$store.state.im.myInfo
    },
    userInfos () {
      return this.$store.state.im.userInfos
    },
    robotInfos () {
      return this.$store.state.im.robotInfos
    },
    msglist () {
      /*let msgs = this.$store.state.currSessionMsgs
      console.log(msgs)
      return msgs*/
      //return this.msglists
    },
    ...mapState({
      currSessionMsgs: state => state.im.currSessionMsgs,
    })
  },
  watch:{
    currSessionMsgs(val,oldVal){
      /*console.log(val,oldVal)
      console.log('---',)*/
      let arr=[...new Set(val)]
      this.msglists.push(...arr)
    },
    scroll(val){
      if(val==0 && this.messageid){
       // let height=document.getElementById('chat-list').offsetHeight
        this.getImHistory().then(async (res)=>{
           /* let afterHeight=await document.getElementById('chat-list').offsetHeight
            let toTop=await afterHeight-height
            document.body.scrollTop=(toTop+200)*/
        })
      }
    },
    msglists(val){
     if(this.isfinish){
       this.$nextTick(()=>{
         this.$store.dispatch('showLoading')
         setTimeout(()=>{
           //this.afterHeight= document.getElementById('chat-list').offsetHeight
           this.afterHeight= document.getElementById('chat-list').scrollHeight
           document.body.scrollTop=(this.afterHeight-this.height)
           this.isfinish=false
           this.$store.dispatch('hideLoading')
         },1000)
       })
     }
    }
  },
  // watch: {
  //   userInfos:{
  //     handler: function(val) {
  //       console.log(val);
  //     },
  //     deep:true
  //   }
  // },
  methods: {
    handleScroll (){
      //this.scroll = window.pageYOffset ||  document.getElementById('chat-list').scrollTop || document.body.scrollTop
      this.scroll = window.pageYOffset ||  document.getElementById('chat-list').scrollTop || document.body.scrollTop || 0
      //console.log(this.scroll)
    },
    async getImHistory(){
      let params={
        jsoncallback:'jsonp',
        OrderID:this.orderId,
        messageid:this.messageid
      }
      if(this.messageid){
        this.height=document.getElementById('chat-list').scrollHeight
      }
      //this.height=document.getElementById('chat-list').offsetHeight
      await api.BuyerCenterApi.getImHistory(params).then(res=>{
        //this.getMsgList=res.body.data.content
        this.messageid=res.body.data.messageid
        this.isfinish=true
          /*if(!this.messageid){
            this.getMsgList=res.body.data.content
          }else{
              this.msglists=[]
              this.getMsgList=[...res.body.data.content,...this.getMsgList]
          }*/
        if(!res.body.data.content && !res.body.data.messageid){
          return
        }else if(!res.body.data.content && res.body.data.messageid){
          this.getImHistory()
        }
        if(res.body.data.content){
          let getUid=this.$getCookie('uid').toLocaleUpperCase()
          let arr=[]
          res.body.data.content.forEach(item=>{
            if(item.SenderID==getUid){
              item.flow='out'
            }else{
              item.flow='in'
            }
            if(item.MsgType=='txt'){
              item.type='text'
              item.showText=item.Msg
            }else if(item.MsgType=='img'){
              item.type='image'
              this.$set(item,'file',new Object())
              this.$set(item.file,'url',item.Msg)
            }
            arr.push(item)
          })
          this.msglists=[...arr,...this.msglists]
          //console.log(this.msglists)
        }

        return res.body.data.content
      })
	  //客服不在线
          if(!this.ispushed){
            if(this.$isLocalStorageSupported && localStorage.getItem('imOrderInfo')) {
              if (JSON.parse(localStorage.getItem('imOrderInfo')).orderInfo.CustomServiceStatus == 2) {
                let date = new Date();
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                let hour = date.getHours();
                let minute = date.getMinutes();
                let second = date.getSeconds();
                let msg = {
                  Msg: "您好！客服暂时已下线您可以继续留言，客服上线后会第一时间给您回复。",
                  MsgType: "txt",
                  ReciveID: this.$getCookie('uid'),
                  ReciveName: null,
                  ReciveTime: "",
                  SendTime: `${year}-${month}-${day}  ${hour}:${minute}:${second}`,
                  SenderID: "",
                  SenderName: null,
                  avatar: "http://shadow.5173.com:8089/dist/im-kfu-t.png",
                  flow: "in",
                  showText: "您好！客服暂时已下线您可以继续留言，客服上线后会第一时间给您回复。",
                  type: "text",
                }
                this.msglists.push(msg)
                this.ispushed=true
              }
            }
          }
      /*let getUid= await this.$getCookie('uid').toLocaleUpperCase()
      if(this.messageid){
        this.getMsgList.forEach(item=>{
          if(item.SenderID==getUid){
            this.$set(item,'flow','out')
          }else{
            this.$set(item,'flow','in')
          }
          if(item.MsgType=='txt'){
            this.$set(item,'type','text')
            console.log()
            this.$set(item,'showText',item.Msg)
          }else if(item.MsgType=='img'){
            this.$set(item,'type','image')
            this.$set(item,'file',new Object())
            this.$set(item.file,'url',item.Msg)
          }
          this.msglists.push(item)
        })
      }*/
    },
    showOrder() {
      this.orderShow = !this.orderShow
    },
    goHistory() {
      this.$router.push({
        name:'chatHistory',
        params: {
          sessionId:this.sessionId.replace('@5173.com','%')
        }
      })
    },
    onClickBack () {
      // location.href = '#/contacts'
      //window.history.go(-1)
      this.isOpen=false
        //this.$router.go(-1)
      history.back()
    },
    msgsLoaded () {
      //pageUtil.scrollChatListDown()
    },
    enterNameCard () {
      if (/^p2p-/.test(this.sessionId)) {
        let account = this.sessionId.replace(/^p2p-/, '')
        if (account === this.$store.state.im.userUID) {
          location.href = `#/general`
          return
        }
        location.href = `#/namecard/${account}`
      }
    },
    getDefaultData: async function getDefaultData() {
      let usertype=JSON.parse(localStorage.getItem('imOrderInfo')).userType
      if(usertype=='buyer'){
        if (this.orderType === 'shouyou') {
          await this.mainShouYouOrderFast({
            orderId: this.orderId,
          })
        } else if(this.orderType === 'mobgoods') {
          await this.getMobOrderDetail({
            orderId: this.orderId,
          })
        } else if(this.orderType === 'pcgoods') {
          await this.mainGoodsOrderDetailed({"jsonStr":{"ServiceType":this.$route.query.ServiceType,"OrderId":this.orderId}})
          await this.getAccountOrderImgInfo({orderId:this.orderId})
        }
      }else if(usertype=='seller'){
        if(this.orderType === 'mobgoods') {
          await this.getDetail(`${this.orderId}_${this.$route.params.id}`)
        }
      }
    },
    ...mapActions({
        mainShouYouOrderFast: 'buyerCenter/GETMAINSHOUYOUFAST',
        getMobOrderDetail: 'buyerCenter/GETMOBORDERDETAIL',
        queryOrderDetail: 'buyerCenter/QUERYORDERDETAIL',
        mainGoodsOrderDetailed: 'buyerCenter/MAINGOODSORDERDETAILED',
        mobileOrderPay: 'buyerCenter/MOBILEORDERPAY',
        openServiceQQ: 'buyerCenter/OPENSERVICEQQ',
        getGoodsEO: 'account/A_GETGOODS',
        getAccountOrderImgInfo: 'buyerCenter/GETPCIMGINFO',
      getDetail:'member/MEMBER_SELLER_ORDER_MOBILE_DETAIL'
    })
  }
}
</script>
<style  src="css/member/member-im.css"></style>
<style scoped>
.top-right a {
  display: inline;
}
</style>
